import fetch from 'node-fetch';

// 通用的发送请求函数
async function sendRequest(url, data) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`);
    }

    const responseBody = await response.json();
    if (responseBody.status !== 1) {
      throw new Error(`API 错误: ${JSON.stringify(responseBody)}`);
    }

    return responseBody;
  } catch (error) {
    console.error('请求错误:', error.message);
    return { error: error.message };
  }
}

// 发送文本信息
async function Text(wexthtml, wxid, msg, atid = "", pid = 0) {
  const data = {
    method: "sendText",
    wxid,
    msg,
    atid,
    pid,
  };

  const responseBody = await sendRequest(wexthtml, data);
  if (!responseBody.error) {
    console.log(`文本发送成功: ${msg}`);
  }
  return responseBody;
}

// 发送图片信息
async function Mage(wexthtml, wxid, img, imgType = 1, pid = 0) {
  const imgTypes = ["url", "file", "base64"];
  const data = {
    method: "sendImage",
    wxid,
    img,
    imgType: imgTypes[imgType - 1],
    pid,
  };

  const responseBody = await sendRequest(wexthtml, data);
  if (!responseBody.error) {
    console.log(`图片发送成功: ${img}`);
  }
  return responseBody;
}

// 发送文件
async function File(wexthtml, wxid, img, pid = 0) {
  const data = {
    method: "sendFile",
    wxid,
    img,
    imgType: "file",
    pid,
  };

  const responseBody = await sendRequest(wexthtml, data);
  if (!responseBody.error) {
    console.log(`文件发送成功: ${img}`);
  }
  return responseBody;
}

// 清理聊天记录
async function chat_logs(wexthtml) {
  const data = {
    method: "ClearMsgList",
    pid: -1,
  };

  const responseBody = await sendRequest(wexthtml, data);
  if (!responseBody.error) {
    console.log('聊天记录清理成功');
  }
  return responseBody;
}

// 任务下载示例
async function example(shpdiz) {
  const taskGroup = await new DownloadTaskGroup()
    .configConfigDir('./temp_repo_log')
    .configMaxWorkerCount(5)
    .configProgressTicktockMillis(500)
    .loadFromConfigDir();

  const task = await taskGroup.newTask(shpdiz, 'mp4', 'ship.mp4');
  await task.start();
  console.log('文件下载成功');
}

// 返回包含功能的对象
async function bot() {
  return { Text, File, Mage, example, chat_logs };
}

export { bot };
